<?php
require_once 'util/class.dbservice.php';

class RelationDao {
	
	 public function getFollowees($userId) {
	 	try {
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return null;
	 		
	 		$relation = $collection->findOne(array('_id'=>$userId));
	 		if($relation==null)
	 			return null;
	 		
	 		if(!array_key_exists('feIds',$relation))
	 			return null;
	 		
	 		return $relation['feIds'];
	 	} catch(Exception $e) {
	 		return null;
	 	}
	 }
	 
	 public function getFollowers($userId) {
	 	try {
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return null;
	 	
	 		$relation = $collection->findOne(array('_id'=>$userId));
	 		if($relation==null)
	 			return null;
	 	
	 		if(!array_key_exists('flIds',$relation))
	 			return null;
	 	
	 		return $relation['flIds'];
	 	} catch(Exception $e) {
	 		return null;
	 	}
	 }
	 
	 public function addRelation($followee, $follower) {
	 	try {
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return Constants::$ERROR_DB;
	 		
	 		$collection->update(array('_id'=>$followee), 
	 				array('$addToSet'=>array('flIds'=>$follower)),
	 				array('upsert'=>true));
	 		
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return Constants::$ERROR_DB;
	 		$collection->update(array('_id'=>$follower),
	 				array('$addToSet'=>array('feIds'=>$followee)),
	 				array('upsert'=>true));
	 		return Constants::$SUCCESS;
	 	} catch(Exception $e) {
	 		return Constants::$ERROR_EXCEPTION;
	 	}
	 }
	 
	 public function removeRelation($followee, $follower) {
	 try {
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return Constants::$ERROR_DB;
	 		
	 		$collection->update(array('_id'=>$followee), 
	 				array('$pull'=>array('flIds'=>$follower)));
	 		
	 		$collection = $this->getCollection();
	 		if(!$collection)
	 			return Constants::$ERROR_DB;
	 		$collection->update(array('_id'=>$follower),
	 				array('$pull'=>array('feIds'=>$followee)));
	 		return Constants::$SUCCESS;
	 	} catch(Exception $e) {
	 		return Constants::$ERROR_EXCEPTION;
	 	}
	 }
	 
	 private function getCollection() {
	 	$db=DBService::getGlobalDb();
	 	return $db->relation;
	 }
}